package com.badboy.servlet;

import com.badboy.entity.Users;
import com.badboy.service.UserService;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    private final UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();

        try {
            // 获取请求参数
            String email = request.getParameter("email");
            String password = request.getParameter("password");

            if (email == null || password == null || email.isEmpty() || password.isEmpty()) {
                result.put("success", false);
                result.put("message", "邮箱和密码不能为空");
                out.print(JSON.toJSONString(result));
                return;
            }

            // 验证登录
            Users user = userService.login(email, password);

            if (user != null) {
                // 登录成功，创建session
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                Cookie  cookie = new Cookie("user",user.getUserId().toString());
                response.addCookie(cookie);
                result.put("success", true);
                result.put("message", "登录成功");
                result.put("user", user);
            } else {
                result.put("success", false);
                result.put("message", "邮箱或密码错误");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "服务器错误: " + e.getMessage());
        } finally {
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
        }
    }

    /**
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doPost(req, resp);
    }
}